package lormi.meipin.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

import java.io.IOException;


/**
 * JSON 工具类
 * */
public class JsonUtil {
	
	private static ObjectMapper jackson = new ObjectMapper();
	private static Gson gson = new Gson();
	
	enum JSONType {
		FASTJSON,GSON,JACKSON
	}
	
	public static String toJSONString(Object obj){
		return toJSONString(obj,JSONType.FASTJSON);
	}
	
	public static String toJSONString(Object obj,JSONType jsonType){
		String result = "";
		switch(jsonType){
		case FASTJSON://com.alibaba.fastjson.JSON;
			result = JSON.toJSONString(obj);
			break;
		case GSON://com.fasterxml.jackson.databind.ObjectMapper;
			try {
				result = jackson.writeValueAsString(obj);
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
			break;
		case JACKSON://com.google.gson.Gson;
			result = gson.toJson(obj);
			break;
		}
		return result;
	}
	
	public static Object stringToObject(String jsonStr,Object obj) {
		return stringToObject(jsonStr,obj,JSONType.FASTJSON);
	}
	
	public static Object stringToObject(String jsonStr,Object obj,JSONType jsonType) {
		Object object = new Object();
		switch(jsonType){
		case FASTJSON://com.alibaba.fastjson.JSON;
			object = JSON.parseObject(jsonStr,obj.getClass());
			break;
		case GSON://com.fasterxml.jackson.databind.ObjectMapper;
			try {
				object = jackson.readValue(jsonStr,obj.getClass());
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		case JACKSON://com.google.gson.Gson;
			object = gson.fromJson(jsonStr,obj.getClass());
			break;
		}
		return object;
	}
	
	public static JSONObject getJsonObject(String str){
		
		return JSON.parseObject(str);
		
	}
	
}
